<?php

namespace App\Jobs;

use App\Models\User;
use App\Service\Redis\RedisBaseService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class UserLearnQuestionCountRankJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @param RedisBaseService $redisBaseService
     * @return void
     * @throws \RedisException
     */
    public function handle(RedisBaseService $redisBaseService)
    {
        // 获取到所有的刷题数
        $allRows = Redis::client()->hGetAll('statistics:userLearnQuestionCount');
        // 查数据库
        if (empty($allRows) || count($allRows) < 15) {
            $userForAll = DB::table('qh_user_learn_question_logs')
                ->selectRaw('userId, COUNT(*) as count')
                ->groupBy('userId')
                ->orderByDesc('count')
                ->limit(15)
                ->pluck('userId', 'count')
                ->toArray();
            if (count($allRows) < 15) {
                foreach ($userForAll as $userId => $count) {
                    if (array_key_exists('userId='.$userId, $allRows)) continue;
                    $allRows['userId='.$userId] = $count;
                }
            }
        }
        // 根据值对数组进行降序排序，保持索引关联
        arsort($allRows);

        // 创建新数组来存储键和值
        $userIds = [];
        foreach ($allRows as $key => $value) {
            $userIds[] = explode('=', $key)[1];
        }
        $userIds = array_slice($userIds, 0, 15);


        $allList = DB::table('user')->select([
            'id',
            'avatar',
            'nickname'
        ])->whereIn('id', $userIds)->get()->sortByDesc(function ($user) use ($userIds, $redisBaseService, $allRows) {
            $user->learnQuestionCount = $redisBaseService->getUserLearnQuestionCount($user->id);
            $user->questionRate = $redisBaseService->getUserQuestionRate($user->id);
            //return $allRows['userId='.$user->id];
            return $user->learnQuestionCount;
        })->values()->toArray();

        // 存入缓存
        \Cache::put('rank:userLearnQuestionCountRank', serialize($allList), 1800);
        Log::debug('[JOB]-userLearnQuestionCountRank:DONE', $allList);
    }
}
